clc
close all
clear 
dbstop if error
%% 输入的范围和步长
x1_min=0;
x1_max=10;
x1_step=2;

x2_min=0;
x2_max=10;
x2_step=10;

x3_min=0;
x3_max=10;
x3_step=2;


%% 输入的参数的数组
x1_list=x1_min:x1_step:x1_max;
x2_list=x2_min:x2_step:x2_max;
x3_list=x3_min:x3_step:x3_max;


%% 遍历参数列表
filename='qiyueqi_R2023a.mdl';
for i=1:length(x1_list)
    assignin("base",'x1',x1_list(i));
    for j=1:length(x2_list)
        assignin("base",'x2',x2_list(j));
        for k=1:length(x3_list)
            assignin("base",'x3',x3_list(k));
            res=sim(filename);
            o1=res.ScopeData.signals(1).values;
            o2=res.ScopeData.signals(2).values;
            o3=res.ScopeData.signals(3).values;
            H1=max(o1)-min(o1);
            H2=max(o2)-min(o2);
            H3=max(o3)-min(o3);     %% 评价指标！！！
            if H1<0.8 && H2<0.8 && H3<0.8
                fit(i,j,k)=H1+H2+H3;    %% 读取返回值 得到幅值绝对值和
            else 
                fit(i,j,k)=9999;
            end

        end
    end
end


%% 找到最小输出和的值 和对应的参数的序号
[minVal, linearInd] = min(fit(:));

% 将线性索引转换为三维索引
[x, y, z] = ind2sub(size(fit), linearInd);




bestX1=x1_list(x);
bestX2=x2_list(y);
bestX3=x3_list(z);
assignin("base",'x1',bestX1);
assignin("base",'x2',bestX2);
assignin("base",'x3',bestX3);

% 显示结果
fprintf('幅值绝对值和最小值：%f\n', minVal);
fprintf('最小值参数：x1 = %d, x2 = %d, x3 = %d\n', bestX1, bestX2, bestX3);

fprintf('最小值参数：x1 = %.5f, x2 = %.5f, x3 = %.5f\n', bestX1, bestX2, bestX3);